package com.zzzzzz.account.signup;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresGuest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.zzzzzz.account.signin.OnlineService;
import com.zzzzzz.account.ticket.ExpiredTicketException;
import com.zzzzzz.account.ticket.NoSuchTicketException;
import com.zzzzzz.account.ticket.TicketDao;
import com.zzzzzz.account.user.User;
import com.zzzzzz.account.user.UserAlreadyExistsException;
import com.zzzzzz.account.user.UserDao;
import com.zzzzzz.common.message.Message;
import com.zzzzzz.common.util.Constants;
import com.zzzzzz.core.web.BaseController;

@Controller
public class SignupController extends BaseController {

	@Resource
	private UserDao userDao;

	@Resource
	private SignupService signupService;
	
	@Resource
	private OnlineService onlineService;
	
	@Resource
	private TicketDao ticketDao;

	@Resource
	private MessageSource messageSource;
	
	@RequiresGuest
	@RequestMapping(value = "/signup", method = RequestMethod.GET)
	public String signupPage(@ModelAttribute SignupForm signupForm) {
		return "account/signup";
	}

	@RequiresGuest
	@RequestMapping(value = "/signup", method = RequestMethod.POST)
	public String signup(Model model, @Valid SignupForm signupForm, BindingResult bindingResult, HttpServletRequest request) {
		if (bindingResult.hasErrors()) {
			return signupPage(signupForm);
		}
		
		try {
			User user = new User();
			signupForm.updateUser(user);
			signupService.add(user);
			signupService.sendAccountActivationEmail(user.getUserId(), request);
		} catch (UserAlreadyExistsException e) {
			bindingResult.rejectValue("email", "message.account.error.email.duplicate");
			return signupPage(signupForm);
		}		

		model.addAttribute("email", signupForm.getEmail());

		return "account/signup_success";
	}

	@RequestMapping(value = "/account/is_email_existing", method = RequestMethod.GET)
	public @ResponseBody
	boolean isEmailExisting(@RequestParam(value = "email", required = true) String email, Model model, HttpServletRequest request) throws Exception {
		boolean isEmailExisting = false;
		isEmailExisting = userDao.isEmailExisting(email);
		return !isEmailExisting;
	}

	@RequestMapping(value = "/account/activate/{token}", method = RequestMethod.GET)
	public String activate(RedirectAttributes redirectAttributes, @PathVariable String token, HttpServletRequest request) {
		if(onlineService.isSignedIn()) {
			redirectAttributes.addFlashAttribute("您已登录");
			return "redirect:/";
		}
		try {
			String userId = ticketDao.findClassPKByKey(token, Constants.TICKET_TYPE.ACCOUNT_ACTIVATION);
			signupService.activate(userId);
			ticketDao.delByKey(token);
			redirectAttributes.addFlashAttribute("msg_success_activate_account", messageSource.getMessage("message.success.activate.account", new Object[] {}, RequestContextUtils.getLocale(request)));
			return "redirect:/login";
		} catch (NoSuchTicketException e) {
			redirectAttributes.addFlashAttribute(Message.error("Your activate password session has expired.  Please try again."));
		} catch (ExpiredTicketException e) {
			String resendActivationEmailURL = request.getContextPath() + "/account/resend_activation_email/" + token;
			redirectAttributes.addFlashAttribute("msg_alert_account_activate_token_expired", messageSource.getMessage("message.alert.account.activate.token.expired", new Object[] { resendActivationEmailURL }, RequestContextUtils.getLocale(request)));
		}
		return "account/signup_guide";
	}

	@RequestMapping(value = "/account/resend_activation_email/{token}", method = RequestMethod.GET)
	public String processResendActivationEmail(RedirectAttributes redirectAttributes, @PathVariable String token, HttpServletRequest request) {
		try {
			String userId = ticketDao.findClassPKByKey(token, Constants.TICKET_TYPE.ACCOUNT_ACTIVATION);
			signupService.sendAccountActivationEmail(userId, request);
			ticketDao.delByKey(token);
		} catch (NoSuchTicketException e) {
			redirectAttributes.addFlashAttribute(Message.error("Your activate password session has expired.  Please try again."));
		} catch (ExpiredTicketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// token expired, resend activation email and redirect to
		// login page
		
		redirectAttributes.addFlashAttribute("msg_success_resend_activation_email", messageSource.getMessage("message.success.resend.activation.email", new Object[] {}, RequestContextUtils.getLocale(request)));
		return "redirect:/login";
	}

	@RequestMapping(value = "/terms_of_service", method = RequestMethod.GET)
	public String viewTermsOfServicePage(Model model) {
		return "account/terms_of_service";
	}
	
	private static final Logger logger = LoggerFactory.getLogger(SignupController.class);
}
